package org.rabbitmq.test8;

import com.rabbitmq.client.*;
import org.rabbitmq.utils.RabbitMqUtils;

import java.util.HashMap;
import java.util.Map;

public class Consumer01 {
    //普通交换机名称
    public static final String NORMAL_EXCHANGE = "normal_exchange";
    //死信交换机名称
    public static final String DEAD_EXCHANGE = "dead_exchange";
    //普通队列名称
    public static final String NORMAL_QUEUE = "normal_queue";
    //死信队列名称
    public static final String DEAD_QUEUE = "dead_queue";

    public static void main(String[] args) throws Exception {
        Channel channel = RabbitMqUtils.getChannel();
        Map<String, Object> arguments = new HashMap<>();
       //1.过期时间
//        arguments.put("x-message-tt1",10000);
        //正常队列设置死信交换机
        arguments.put("x-dead-letter-exchange",DEAD_EXCHANGE);
        //设置死信Routingkey
        arguments.put("x-dead-letter-routing-key","list");
        //设置队列最大消息数量
//        arguments.put("x-max-length",6);
        //声明交换机死信和普通的类型为direct
        channel.exchangeDeclare(NORMAL_EXCHANGE, BuiltinExchangeType.DIRECT);
        channel.exchangeDeclare(DEAD_EXCHANGE, BuiltinExchangeType.DIRECT);
        //声明和普通队列
        channel.queueDeclare(NORMAL_QUEUE,false,false,false,arguments);
        //死信队列
        channel.queueDeclare(DEAD_QUEUE,false,false,false,null);
        //绑定普通的交换机与队列
        channel.queueBind(NORMAL_QUEUE,NORMAL_EXCHANGE,"zhangsan");
        //绑定死信的交换机与队列
        channel.queueBind(DEAD_QUEUE,DEAD_EXCHANGE,"list");
        System.out.println("等待接收消息....");
        DeliverCallback deliverCallback = (consumerTag,message) ->{
            String message1 = new String(message.getBody(),"UTF-8");
            if (message1.equals("info5")){
                System.out.println("消息被拒绝了"+message1);
                channel.basicReject(message.getEnvelope().getDeliveryTag(),false);
            }else {
                System.out.println("01接收到消息：" + message1);
                channel.basicAck(message.getEnvelope().getDeliveryTag(),false);
            }
        };
//开启手动应达
        channel.basicConsume(NORMAL_QUEUE,false, deliverCallback, consumerTag->{});
    }
}
